package com.search.dynamics.samples.spring.controller;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;


public class DemoSolrController extends MultiActionController{

	private SolrServer solrServer;

	public ModelAndView input(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
		ModelAndView mav = new ModelAndView("/WEB-INF/solr_pages/search_input.jsp");
		return mav;
	}

	public ModelAndView search(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String what=request.getParameter("what");
		String where=request.getParameter("where");
		String responseMessage=null;
		SolrQuery solrQuery = null;
		ModelAndView mav = new ModelAndView("/WEB-INF/solr_pages/search_result.jsp");
		if(StringUtils.hasText(what) && StringUtils.hasText(where)) {
			solrQuery=new SolrQuery("doc_type:"+what+" && "+"doc_place:"+where);
			responseMessage="Search Result for What=<b>"+what+"</b>, and Where=<b>"+where+"</b>";
		} else if(StringUtils.hasText(what) && !StringUtils.hasText(where)) {
			solrQuery=new SolrQuery("doc_type:"+what);
			responseMessage="You did not provided valid WHERE term, partial search performed for WHAT term";
		} else if(!StringUtils.hasText(what) && StringUtils.hasText(where)) {
			solrQuery=new SolrQuery("doc_place:"+where);
			responseMessage="You did not provided valid WHAT term, partial search performed for WHERE term";
		} else {
			responseMessage="You did not provided valid WHERE and WHAT term, partial search performed";
		}
		if(solrQuery!=null){
			QueryResponse solrResponse = getSolrServer().query(solrQuery);
			List<Document> beans = solrResponse.getBeans(Document.class);
			System.out.println("Search for '" + solrQuery + "': found " + beans.size() + " beans.");
			mav.addObject(WebConstants.SOLR_SEARCH_RESULT, beans);
		}
		mav.addObject(WebConstants.SOLR_SEARCH_RESULT_MESSAGE, responseMessage);

		return mav;
	}

	public SolrServer getSolrServer() {
		return solrServer;
	}
	public void setSolrServer(SolrServer solrServer) {
		this.solrServer = solrServer;
	}
}